/**
 * 
 */
package org.lightcommons.template.commontemplate;

import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.commontemplate.core.Context;
import org.commontemplate.core.ContextFactory;
import org.commontemplate.core.Template;
import org.commontemplate.tools.web.EngineHolder;
import org.commontemplate.tools.web.ModelMap;
import org.lightcommons.template.AbstractTemplate;
import org.lightcommons.util.Assert;

/**
 * @author gl
 * @since Jun 16, 2008
 */
public class CommonTemplateFacade extends AbstractTemplate {

	private final Template template;
	private final ContextFactory contextFactory;

	public CommonTemplateFacade(final Template template, final ContextFactory contextFactory) {
		super();
		Assert.notNull(template,"template must not be null");
		this.template = template;
		this.contextFactory = contextFactory;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void renderUnsafe(Object rootMap, Writer writer,Locale locale) throws Exception {
		if(rootMap instanceof Context){
			template.render((Context) rootMap);
		}else{
			final Context context = contextFactory.createContext(writer);
			context.setLocale(locale);
			if (rootMap instanceof Map) {
				context.pushLocalContext((Map) rootMap);
			} else {
				context.pushLocalContext(new ModelMap(rootMap));
			}
			template.render(context);
		}
	}

}
